package com.lagou.filter;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/7/25.
 * Time: 3:02.
 * Tags: Code, we are serious.
 */

import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author
 * @create 2020-07-25 3:02
 **/
public class AuthCookiePorcessFilter  implements GlobalFilter, Ordered {
    @Value("${config.cookie.name.auth}")
    private String authTagName;

    @Value("${config.cookie.name.token}")
    private String tokenTagName;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpResponseDecorator newResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (this.getHeaders().containsKey(authTagName)) {
                    processAuthCookie(this);
                }
                return super.writeWith(body);
            }
        };

        return chain.filter(exchange.mutate().response(newResponse).build());
    }

    @Override
    public int getOrder() {
        return -2;
    }

    private void processAuthCookie(ServerHttpResponseDecorator response) {
        String auth = response.getHeaders().getFirst(authTagName);
        if ("".equals(auth)) {
            response.addCookie(
                    ResponseCookie.from(tokenTagName, "")
                            .path("/")
                            .maxAge(0)
                            .build()
            );
        } else {
            response.addCookie(
                    ResponseCookie.from(tokenTagName, auth)
                            .path("/")
                            .build()
            );
        }
        response.getHeaders().remove(authTagName);
    }
}
